#include <stdlib.h>
#include <string.h>
#include "linked-queue.h"

int InitQueue(LnkQueue *queue){
    if (queue) {
        queue->front = NULL;
        queue->rear = NULL;
        return (0);
    } else{
        return(-1);
    }
}

int DestroyQueue(LnkQueue *queue){
    if (queue && queue->front){
        LnkNode *p_current = queue->front,*p_next;
        while (p_current){
            p_next = p_current->next_node;
            free(p_current);
            p_current = p_next;
        }
        queue->front = NULL;
        queue->rear = NULL;
        return(0);
    } else{
        return(-1);
    }
}

int ClearQueue(LnkQueue *queue){
    return(DestroyQueue(queue));
}

int QueueEmpty(LnkQueue queue){
    return(queue.front == NULL && queue.rear == NULL);
}

int GetHead(LnkQueue queue,ElemType *element){
    if (queue.front && queue.rear){
        memcpy(element,&queue.front->node_value, sizeof(ElemType));
        return(0);
    } else{
        return(-1);
    }
}

int EnQueue(LnkQueue *queue,ElemType element){   //Bad!!!
    if (queue && queue->front && queue->rear){
        queue->rear->next_node = malloc(sizeof(LnkNode));
        queue->rear =  queue->rear->next_node;
        queue->rear->next_node = NULL;
        memcpy(&queue->rear->node_value,&element, sizeof(ElemType));
        return(0);
    } else if (queue && queue->front == NULL && queue->rear == NULL){
        queue->front = malloc(sizeof(LnkNode));
        queue->front->next_node = NULL;
        memcpy(&queue->front->node_value,&element, sizeof(ElemType));
        queue->rear = queue->front;
        return(0);
    }else{
        return(-1);
    }
}

int DeQueue(LnkQueue *queue,ElemType *element){
    if (queue && queue->front && queue->rear){
        LnkNode *p_next = queue->front->next_node;
        memcpy(element,&queue->front->node_value, sizeof(ElemType));
        free(queue->front);
        queue->front = p_next;
        return(0);
    } else{
        return(-1);
    }
}
int QueueLength(LnkQueue queue){
    int count = 0;
    LnkNode *p_current = queue.front;
    while (p_current){
        ++count;
        p_current = p_current->next_node;
    }
    return(count);
}